/**
 * 
 */
package com.zx.web.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.zx.web.utils.FilePathUtils;
import com.zx.web.utils.UUIDUtils;

/**
 * 文件上传
 * 
 * @author hb
 *
 *         2017年8月17日 下午8:53:52
 */
@WebServlet("*.up")
@MultipartConfig(fileSizeThreshold = 0)
public class FileUploadAction extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		PrintWriter out = response.getWriter();

		String path = request.getServletPath();
		if ("/add.up".equals(path)) {
			// 1.获得普通的表单域
			String pname = request.getParameter("pname");
			System.out.println(pname);
			// 2.获得文件域的数据:采用javaEE6.0中扩展的getPart方法,Part对象封装了文件的字节流
			Part part = request.getPart("pic");
			System.out.println(part);
			// 3. 获得文件保存的路径
			String dirPath = getServletContext().getRealPath("images");
			// 4. 获得请求头为Content-Disposition的值
			String disposition = part.getHeader("Content-Disposition");
			System.out.println(disposition);
			String fileName = parseFileName(disposition);
			String uuidFileName=UUIDUtils.fileNameUUID(fileName);
			//获得文件的路径
			String uuidPath=FilePathUtils.parsePath(uuidFileName);
			//创建该路径
			File dir=new File(dirPath+uuidPath);
			if(!dir.exists()){
				dir.mkdirs();
			}
			String filePath = dirPath+uuidPath + "/" +uuidFileName ;

			System.out.println(filePath);

			// 5. 写入到文件夹
			part.write(filePath);
			out.println("文件上传成功!");
		}
	}

	// form-data; name="pic"; filename="ss.xml"
	private String parseFileName(String disposition) {
		String fileName = null;
		String[] datas = disposition.split(";");
		for (String d : datas) {
			if (d.contains("filename")) {
				fileName = d.substring(d.indexOf("=") + 1);

			}
		}
		return fileName.replaceAll("\"", "");
	}
}
